package main

import (
	"flag"
	"fmt"
	"google.golang.org/grpc"
	"net"
	"service_base_shop/user_srv/Handler"
	"service_base_shop/user_srv/Initialize"
	"service_base_shop/user_srv/Proto"
)
func GetFreePort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		return 0, err
	}

	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return 0, err
	}
	defer l.Close()
	return l.Addr().(*net.TCPAddr).Port,  nil
}

func main()  {
	IP := flag.String("ip", "0.0.0.0", "ip地址")
	Port := flag.Int("port", 8081, "端口号")
	flag.Parse()
	if *Port == 0{
		*Port, _ = GetFreePort()
	}
	//设置日志
	initialize.InitLogger()

	//设置配置文件
	initialize.InitConfig()

	//初始化数据库
	initialize.InitDB()

	//初始化grpc 服务
	server := grpc.NewServer()

	//注册
	protopb.RegisterUserServer(server,&handler.User{})

	fmt.Println(*IP,*Port)

	//监听
	lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *IP, *Port))
	if err != nil {
		panic(err)
	}
	//启动
	server.Serve(lis)
}
